package com.ganzalang.gmall.command.inventory.factory;

import com.ganzalang.gmall.command.api.dto.SubOrderVariantDTO;
import com.ganzalang.gmall.command.domain.ProductVariantInventory;
import com.ganzalang.gmall.command.inventory.updater.InventoryUpdater;
import com.ganzalang.gmall.command.inventory.updater.VerifySaleInventoryUpdater;
import com.ganzalang.gmall.command.service.ProductVariantInventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: saas-shoplus-product-parent
 * @description: 比较库存命令工厂方法,只做比较,不做处理
 * @author: jingyang
 * @create: 2020-08-13 14:29
 **/
@Component
public class VerifySaleInventoryUpdaterFactory<T> extends AbstractInventoryUpdaterFactory<T>{

    /**
     * 注入库存服务组件
     * @param inventoryService 库存服务组件
     * @param publisher 事件发布组件
     */
    @Autowired
    public VerifySaleInventoryUpdaterFactory(
            ProductVariantInventoryService inventoryService,
            ApplicationEventPublisher publisher) {
        super(inventoryService, publisher);
    }

    /**
     * 获取商品库存对象集合
     * @param parameter 每个命令对应的参数
     * @return sku ids集合
     */
    @Override
    protected List<ProductVariantInventory> createGoodsStockDOs(T parameter) {
        List<SubOrderVariantDTO> subOrderVariantDTOS = (List<SubOrderVariantDTO>) parameter;
        return subOrderVariantDTOS.stream().map(subOrderVariantDTO -> subOrderVariantDTO.clone(ProductVariantInventory.class)).collect(Collectors.toList());
    }

    /**
     * 创建库存更新命令
     * @param productVariantInventories 商品sku库存集合
     * @param parameter 每个命令对应的参数
     * @param shopId 店铺ID
     * @return 库存更新命令
     */
    @Override
    protected InventoryUpdater create(List<ProductVariantInventory> productVariantInventories, T parameter, Long shopId) {
        List<SubOrderVariantDTO> subOrderVariantDTOS = (List<SubOrderVariantDTO>) parameter;
        Map<Long, SubOrderVariantDTO> subOrderVariantDTOMap = subOrderVariantDTOS.stream().collect(Collectors.toMap(SubOrderVariantDTO::getSkuId, v -> v, (v1, v2) -> {
            v1.setQuantity(v1.getQuantity() + v2.getQuantity());
            return v1;
        }));
        return new VerifySaleInventoryUpdater(inventoryService, productVariantInventories, subOrderVariantDTOMap, publisher, shopId);
    }
}
